package com.spring.demo.rabbit.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.spring.demo.rabbit.QueueConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/***
 * @title RalayListener
 * @description
 * @author baiji
 * @version 1.0.0
 * @create 2023/9/7 11:53
 **/
@Slf4j
@Component
public class RelayListener {

    @RabbitListener(queues = QueueConst.DELAY_QUEUE)
    public void handler(Message message, Channel channel) throws IOException {
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("收到延迟消息: {}", body);
        log.info("延迟消息附带的头消息： {}", JSON.toJSONString(message.getMessageProperties().getHeaders()));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("延迟消息消费失败：{}", e.getMessage());
            // 消息消费异常后，返回一个nack响应
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
